export default class MyPromise {
    static PENGDING = 'pending';
    static FULFILLED = 'fulfilled';
    static REJECTED = 'rejected';

    constructor(executor) {
        this.status = MyPromise.PENGDING;
        this.value = null;
        this.callback = [];
        executor(this.resolve.bind(this), this.reject.bind(this));
    }

    resolve(value) {
        this.value = value;
        this.status = MyPromise.FULFILLED;
        setTimeout(() => {
            this.callback.map((callback) => callback.resolvefun(this.value)); 
        });
    }

    reject(value) {
        this.value = value;
        this.status = MyPromise.REJECTED;
        setTimeout(() => {
            this.callback.map((callback) => callback.rejectedfun(this.value));
        })
    }

    then(resolvefun, rejectedfun) {
        if (typeof resolvefun !== 'function') {
            resolvefun = (value) => value;
        }
        if (typeof rejectedfun !== 'function') {
            rejectedfun = (value) => value;
        }
        // this.callback.push({ resolvefun, rejectedfun });
        return new MyPromise((resolve,rejected)=>{
            this.callback.push({ 
                resolvefun:value=>{
                    let result=resolvefun(value)
                    if (result instanceof MyPromise) {
                        result.then(value=>{
                            resolve(value)
                        })
                    }
                    else {
                        resolve(result)
                    }
                }, 
                rejectedfun:value=>{
                    let result=rejectedfun(value)
                    resolve(result)
                }
            },
               
            );
        })
    }
}
